package com.cmc.cloud.cmclink.doc.controller.admin.special;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.cmc.cloud.cmclink.doc.constants.errorconstant.DgCommodityErrorCodeConstants;import com.cmc.cloud.cmclink.doc.mapper.DgCommodityMapper;import com.cmes.framework.common.exception.util.ServiceExceptionUtil;import jodd.util.StringUtil;import org.apache.tika.utils.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.cmc.cloud.cmclink.doc.constants.UrlConstants;
import com.cmc.cloud.cmclink.doc.convert.DgCommodityConvert;
import com.cmc.cloud.cmclink.doc.convert.DgProhibitedItemConvert;
import com.cmc.cloud.cmclink.doc.dto.DgCommodityGetDto;
import com.cmc.cloud.cmclink.doc.entity.DgCommodityDO;
import com.cmc.cloud.cmclink.doc.framework.listener.DgCommodityExcelListener;
import com.cmc.cloud.cmclink.doc.service.DgCommodityService;
import com.cmc.cloud.cmclink.doc.util.sepcial.DgCommodityUtil;
import com.cmc.cloud.cmclink.doc.vo.special.dgcommoditypsnvo.DgCommodityPsnRespVO;
import com.cmc.cloud.cmclink.doc.vo.special.dgcommodityvo.DgCommodityExportExcelVO;
import com.cmc.cloud.cmclink.doc.vo.special.dgcommodityvo.DgCommodityImportExcelVO;
import com.cmc.cloud.cmclink.doc.vo.special.dgcommodityvo.DgCommodityPageReqVO;
import com.cmc.cloud.cmclink.doc.vo.special.dgcommodityvo.DgCommodityRespVO;
import com.cmes.framework.biz.advice.annotations.UseResponsePropertyAdvice;
import com.cmes.framework.common.pojo.CommonResult;
import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.excel.core.util.ExcelUtils;
import com.cmes.framework.operatelog.core.annotations.OperateLog;
import com.cmes.framework.operatelog.core.enums.OperateTypeEnum;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * 危险品品名库前端接口Controller
 * 
 * @author codegen
 */
@Tag(name = "管理后台 - 危险品品名库")
@RestController
@Validated
@RequestMapping(UrlConstants.APPLICATION_URL + "/special/dg-commodity")
@Slf4j
public class DgCommodityController {

    @Resource
    private DgCommodityService dgCommodityService;@Autowired private DgCommodityMapper dgCommodityMapper;

    @Operation(summary = "获得危险品品名库")
    @GetMapping("/get/{id}")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @UseResponsePropertyAdvice
    public CommonResult<DgCommodityRespVO> getDgCommodity(@PathVariable("id") Long id) {
        DgCommodityGetDto dgCommodityGetDto = dgCommodityService.getDgCommodity(id);
        DgCommodityRespVO respVO = DgCommodityConvert.INSTANCE.convert(dgCommodityGetDto.getDgCommodityDO());
        List<DgCommodityPsnRespVO> dgCommodityPsnRespVOList =
            DgProhibitedItemConvert.INSTANCE.convertPsnVOList(dgCommodityGetDto.getDgCommodityPsnDOList());
        respVO.setDgCommodityPsnRespVOList(dgCommodityPsnRespVOList);
        return CommonResult.success(respVO);
    }

    @Operation(summary = "获得危险品品名库分页")
    @PostMapping("/page")
    @UseResponsePropertyAdvice
    public CommonResult<PageResult<DgCommodityRespVO>>
        getDgCommodityPage(@Valid @RequestBody DgCommodityPageReqVO pageVO) {
        PageResult<DgCommodityDO> pageResult = dgCommodityService.getDgCommodityPage(pageVO);
        List<DgCommodityRespVO> results = DgCommodityConvert.INSTANCE.convertList(pageResult.getList());
        return CommonResult.success(new PageResult<>(results, pageResult.getTotal()));
    }

    @GetMapping("/excel-template")
    @Operation(summary = "下载excel导入模板")
    public void exportExcelTemplate(HttpServletResponse response) throws IOException {
        List<DgCommodityExportExcelVO> dgCommodityExportExcelVOList = new ArrayList<>();
        // 一定要向response写数据之前设置响应头，否则会出现文件下载失败
        response.addHeader("Content-Disposition",
            "attachment;filename=" + URLEncoder.encode("危险品品名模版.xlsx", StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        ExcelUtils.write(response, "dgCommodityTemplate.xls", "commodity", DgCommodityExportExcelVO.class,
                dgCommodityExportExcelVOList);
    }

    @GetMapping("/excel-export")
    @Operation(summary = "excel导出")
    public void exportExcel(HttpServletResponse response, @RequestParam("versionNo") String versionNo)
        throws IOException {
        if (StringUtils.isEmpty(versionNo)) {
            versionNo = dgCommodityMapper.getLatestVersion();
            if (StringUtils.isEmpty(versionNo)) {
                throw ServiceExceptionUtil.exception(DgCommodityErrorCodeConstants.DG_COMMODITY_VERSION_NOT_EXIST);
            }
        } else {
            DgCommodityUtil.validVersionValid(versionNo);
        }
        List<DgCommodityDO> dgCommodityDOList = dgCommodityService.getExportList(versionNo);
        List<DgCommodityExportExcelVO> exportList = DgCommodityConvert.INSTANCE.convertExcelList(dgCommodityDOList);
        // 一定要向response写数据之前设置响应头，否则会出现文件下载失败
        response.addHeader("Content-Disposition",
            "attachment;filename=" + URLEncoder.encode("危险品品名.xlsx", StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        ExcelUtils.write(response, "dgCommodity.xls", "commodity", DgCommodityExportExcelVO.class, exportList);
    }

    @OperateLog(type = OperateTypeEnum.CREATE)
    @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "excel新增导入")
    public CommonResult<Integer> excelCreateImport(@RequestPart @RequestParam(value = "file") MultipartFile file,
        @RequestParam("versionNo") String versionNo) throws IOException {
        DgCommodityUtil.validVersionValid(versionNo);
        DgCommodityExcelListener dgCommodityExcelListener = new DgCommodityExcelListener(new ArrayList<>());
        List<DgCommodityImportExcelVO> dgCommodityImportExcelVOList =
            EasyExcel.read(file.getInputStream(), DgCommodityImportExcelVO.class, dgCommodityExcelListener)
                .autoCloseStream(true).doReadAllSync();
        Integer num = dgCommodityService.saveImportData(dgCommodityImportExcelVOList, versionNo);
        return CommonResult.success(num);
    }

    @Operation(summary = "版本是否存在, 存在返回true, 不存在返回false")
    @GetMapping("/version/exist")
    public CommonResult<Boolean> versionExist(@Valid @RequestParam("versionNo") String versionNo) {
        Boolean exist = dgCommodityService.versionExist(versionNo);
        return CommonResult.success(exist);
    }
}
